package utils

import (
	"database/sql/driver"
	"fmt"
	"time"
)

func NewJsonDateNow() *JSONDate         { return NewJsonDate(time.Now().Local()) }
func NewJsonDate(t time.Time) *JSONDate { return &JSONDate{Time: t} }
func NewJsonDateStr(t string) (*JSONDate, error) {
	n := &JSONDate{}
	err := n.UnmarshalJSON([]byte(t))
	return n, err
}

// JSONDate format json time field by myself
type JSONDate struct {
	time.Time
}

// MarshalJSON on JSONDate format Time field with %Y-%m-%d %H:%M:%S
func (t JSONDate) MarshalJSON() ([]byte, error) {
	if (t == JSONDate{}) {
		formatted := fmt.Sprintf("\"%s\"", "")
		return []byte(formatted), nil
	} else {
		formatted := fmt.Sprintf("\"%s\"", time.DateOnly)
		return []byte(formatted), nil
	}
}
func (t *JSONDate) UnmarshalJSON(data []byte) (err error) {
	now, _ := time.ParseInLocation(`"2006-01-02"`, string(data), time.Local)
	t.Time = now
	return
}

// Value insert timestamp into mysql need this function.
func (t JSONDate) Value() (driver.Value, error) {
	var zeroTime time.Time
	if t.Time.UnixNano() == zeroTime.UnixNano() {
		return nil, nil
	}
	return t.Time, nil
}

// Scan valueof time.Time
func (t *JSONDate) Scan(v interface{}) error {
	value, ok := v.(time.Time)
	if ok {
		*t = JSONDate{Time: value}
		return nil
	}
	return fmt.Errorf("can not convert %v to timestamp", v)
}
